package org.facyt.commons.view.form;

import java.util.HashMap;
import java.util.Map;

import org.facyt.commons.util.VaadinUtil;

import com.vaadin.data.Item;
import com.vaadin.ui.AbstractTextField;
import com.vaadin.ui.Component;
import com.vaadin.ui.DefaultFieldFactory;
import com.vaadin.ui.Field;

public class GenericFieldFactory extends DefaultFieldFactory {

	private static final long serialVersionUID = 6298375376114910651L;
	
	private Map<Object, FieldGenerator> mapFieldGenerator = new HashMap<Object, FieldGenerator>();
	private Map<String, String> captionFields = new HashMap<String, String>();
	private Map<String, Boolean> readOnlyFields = new HashMap<String, Boolean>();
	private Map<String, Boolean> requiredFields = new HashMap<String, Boolean>();
	
	@Override
	public final Field createField(Item item, Object propertyId, Component uiContext) {

		Field field = null;

		FieldGenerator fieldGenerator = mapFieldGenerator.get(propertyId);
		
		if (fieldGenerator != null) {
			field = fieldGenerator.createField(item, propertyId, uiContext);
		} else {
			field = super.createField(item, propertyId, uiContext);
		}
		
		if (field != null && captionFields.containsKey(propertyId))
			field.setCaption(VaadinUtil.getProperties(captionFields.get(propertyId)));

		if (field != null && AbstractTextField.class.isAssignableFrom(field.getClass())) {
			((AbstractTextField) field).setNullRepresentation("");
			((AbstractTextField) field).setNullSettingAllowed(true);
		}
		
		if (field != null && readOnlyFields != null && readOnlyFields.containsKey(propertyId)){
			field.setReadOnly(readOnlyFields.get(propertyId));
		}
		
		if (field != null && requiredFields != null && requiredFields.containsKey(propertyId)){
			field.setRequired(requiredFields.get(propertyId));
			field.setRequiredError(VaadinUtil.getProperties("form.campo.requerido", field.getCaption()));
		}
		
		return field; 
	}

	public void addFieldGenerator(Object propertyId, FieldGenerator fieldGenerator) {
		this.mapFieldGenerator.put(propertyId, fieldGenerator);
	}
	
	public void setCaptionFields(Map<String, String> captionFields) {
		this.captionFields = captionFields;
	}
	
	public Map<String, Boolean> getRequiredFields() {
		return requiredFields;
	}
	
	public void setRequiredFields(Map<String, Boolean> requieredFields) {
		this.requiredFields = requieredFields;
	}
	
	public void setReadOnlyFields(Map<String, Boolean> readOnlyFields) {
		this.readOnlyFields = readOnlyFields;
	}
	
	public Map<String, Boolean> getReadOnlyFields() {
		return readOnlyFields;
	}

}
